package com.dj.product.k2faas.view.datasource;

import com.dj.product.k2faas.entity.datasource.DataSource;
import com.dj.product.k2faas.common.exception.NotFoundException;
import com.dj.product.k2faas.jpa.PredicateWrapperBuilder;
import com.dj.product.k2faas.jpa.dto.QueryArg;
import com.dj.product.k2faas.jpa.view.CommonView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

/**
 * Created by 丁建 on 2025/9/23 09:26
 *
 * @author 丁建
 */
@Component
class DefaultDataSourceView implements DataSourceView {

    @Autowired
    private DataSourceRepository dataSourceRepository;

    @Autowired
    private CommonView commonView;

    @Override
    public DataSource findByName(String name) {
        return dataSourceRepository.findByName(name).orElseThrow(() -> new NotFoundException("未找到名称为：%s的据源".formatted(name)));
    }

    @Override
    public DataSource findById(long dataSourceId) {
        return dataSourceRepository.findById(dataSourceId).orElseThrow(() -> new NotFoundException("未找到ID为：%s的据源".formatted(dataSourceId)));
    }

    @Override
    public DataSource save(DataSource dataSource) {
        return dataSourceRepository.save(dataSource);
    }

    @Override
    public Page<DataSource> findAll(String keyword, Pageable pageable) {
        var spec = PredicateWrapperBuilder.orBuilder(DataSource.class).innerLike(DataSource::getName, keyword).innerLike(DataSource::getUrl, keyword).build();
        return dataSourceRepository.findAll(spec, pageable);
    }

    @Override
    public void updateAllAsNotDefault() {
        var sql = """
                        update data_source set default_connection=false""";
        commonView.update(sql, QueryArg.create());

    }
}
